<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px; padding-bottom:10px; font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主内容区域 -->
    <el-card>
      <!-- 页面标题 -->
      <el-page-header @back="goBack" content="用户列表" style="margin-bottom: 20px;"></el-page-header>

      <!-- 条件查询表单 -->
      <el-form :inline="true" :model="queryMap" ref="searchForm" size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh; color: #1f2d3d">条件查询</h4>
        </el-row>
        <el-row>
          <!-- 客户名称 -->
          <el-col :span="4">
            <el-form-item prop="customerName">
              <el-input v-model="queryMap.clientName" clearable placeholder="请输入客户名称"></el-input>
            </el-form-item>
          </el-col>
          <!-- 用户昵称 -->
          <el-col :span="4">
            <el-form-item prop="userNickname">
              <el-input v-model="queryMap.nickName" clearable placeholder="请输入用户昵称"></el-input>
            </el-form-item>
          </el-col>
          <!-- 用户名 -->
          <el-col :span="4">
            <el-form-item prop="username">
              <el-input v-model="queryMap.userName" clearable placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <!-- 手机号码 -->
          <el-col :span="4">
            <el-form-item prop="phoneNumber">
              <el-input v-model="queryMap.phone" clearable placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="role">
              <el-select
                  filterable
                  style="width: 140px;"
                  placeholder="请选择账号"
                  v-model="queryMap.accountName"
                  @change="getDeptClientList"
              >
                <el-option
                    v-for="(name) in accountName"
                    :key="name"
                    :label="name"
                    :value="name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 状态 -->
          <el-col :span="3">
            <el-form-item prop="status">
              <el-select v-model="queryMap.status" clearable placeholder="请选择状态">
                <el-option label="全部"></el-option>
                <el-option label="未开启外呼" value="0"></el-option>
                <el-option label="已开启外呼" value="1"></el-option>
                <el-option label="冻结" value="-1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top:  -15px">
          <!-- 部门 -->
          <el-col :span="4">
            <el-form-item prop="department">
              <template>
                <!-- 代理所有属性、事件：v-bind="$attrs" v-on="$listeners" -->
                <el-select  ref="select" v-model="selectedItem" placeholder="请选择部门"
                           class="tree-select" >
                  <el-option   style="height: 30vh"
                      class="tree-option view-scroll" >
                    <!-- data：数据-->
                    <!-- props：数据结构配置 -->
                    <!-- node-key：唯一标识字段 -->
                    <el-tree
                        style="height: 10vh"
                        ref="tree" :data="this.deptData" :node-key="option.value" :props="option"
                        class="tree-select-innertree" @current-change="selectDeptID"
                        :highlight-current="true"
                    ></el-tree>
                  </el-option>
                </el-select>
              </template>
<!--              <el-select-->
<!--                  clearable-->
<!--                  style="width: 140px;"-->
<!--                  placeholder="请选择部门"-->
<!--                  v-model="queryMap.deptId"-->
<!--              >-->
<!--                <el-option label="全部"></el-option>-->
<!--                <el-option-->
<!--                    v-for="(dept) in departments"-->
<!--                    :key="dept.deptId"-->
<!--                    :label="dept.deptName"-->
<!--                    :value="dept.deptId">-->
<!--                </el-option>-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>

          <!-- 操作按钮 -->
          <el-col :span="3">
            <div style="display: flex; align-items: center; justify-content: flex-end; height: 40px;">
              <el-button icon="el-icon-refresh" @click="reset" style="background-color: #f0f0f0; color: #409EFF; border: none;">重置</el-button>
              <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 操作按钮区 -->
      <div style="margin-bottom: 10px; display: flex">
        <span class="hint" style="font-size: 11px;margin: 5px">温馨提示：部门只有在账号选择后，才会显示当前账号的所有部门</span>
      </div>

      <!-- 用户表格 -->
      <el-table ref="multipleTable" :data="userData" size="small" @selection-change="handleSelectionChange"
                border style="width: 100%;" height="450">
        <!-- 选择列 -->
        <el-table-column type="selection" width="40"></el-table-column>
        <!-- 客户名称 -->
        <el-table-column prop="clientName" label="客户名称" width="150" fixed="left" sortable></el-table-column>
        <!-- 用户名 -->
        <el-table-column prop="userName" label="用户名" width="120" sortable></el-table-column>
        <!-- 昵称 -->
        <el-table-column prop="nickName" label="昵称" width="120" sortable></el-table-column>
        <!-- 手机号码 -->
        <el-table-column prop="phone" label="手机号码" width="140" sortable></el-table-column>
        <!-- 部门 -->
        <el-table-column prop="departmentName" label="部门" width="150" sortable></el-table-column>
        <!-- 账号名称 -->
        <el-table-column prop="accountName" label="账号名称" width="100" sortable></el-table-column>
        <!-- 座机 -->
        <el-table-column prop="telNumber" label="座机" width="140" sortable></el-table-column>
        <!-- 有效期 -->
        <el-table-column prop="indate" label="有效期" width="150" sortable></el-table-column>
        <!-- 状态 -->
        <el-table-column prop="test" label="状态" width="120" sortable><template v-slot="scope"><span>{{showStatus(scope.row.status)}}</span></template></el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template v-slot="scope">
            <div style="display: flex; justify-content: space-around;">
              <!-- 详情 -->
              <el-tooltip content="详情" placement="top" effect="light">
                <el-button circle round plain size="small" type="primary" icon="el-icon-edit-outline" v-hasPermission="'user:edit'"  @click="selectUserById(scope.row.userId)"></el-button>
              </el-tooltip>
              <!-- 下线按钮 -->
              <el-tooltip content="删除" placement="top" effect="light" v-if="scope.row.type!=0">
                <el-button circle round plain icon="el-icon-delete" type="danger" size="small"  v-hasPermission="'userDelete:delete'" @click="deleteUser(scope.row.userId)"></el-button>
              </el-tooltip>
              <!-- 解冻按钮 -->
              <el-tooltip :content="selectUpdateStatus(scope.row.status)" placement="top" effect="light"  v-if="scope.row.type!=0">
                <el-button circle round plain icon="el-icon-open" :type="(scope.row.status==0 || scope.row.status==1)?'warning':'success'" size="small"  v-hasPermission="'userUpdateStatus:status'" @click="updateStatus(scope.row.userId,scope.row.status)"></el-button>
              </el-tooltip>
              <el-tooltip content="恢复默认密码" placement="top" effect="light">
                <el-button circle round plain icon="el-icon-refresh-right" v-hasPermission="'user:updatePwd'" type="success" size="small" @click="updatePwd(scope.row.userId)"></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

      <el-drawer
          title="用户详情"
          :visible.sync="drawer"
          direction="rtl"
          size="46%"
          >
        <div style="text-align: center;color: #1f2d3d">
          <h2 style="margin: 0" v-text="userForm.clientName">客户名称</h2>
          <div style="color: #5e6d82;font-size: 14px; margin-bottom: 3vh">
            创建时间:<span v-text="userForm.createTime"></span>
          </div>

        </div>
        <div style="height: 70vh;overflow: auto">
          <el-card style="margin: 0 3vh">
            <el-row>
              <el-col :span="8">
                <label>用户名:</label><span v-text="userForm.userName"></span>
              </el-col>
              <el-col :span="8">
               <label>用户昵称:</label><span v-text="userForm.nickName"></span>
              </el-col>
              <el-col :span="8">
                <label>手机号码:</label><span v-text="userForm.phone"></span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <label>座机:</label><span v-text="userForm.telNumber"></span>
              </el-col>
              <el-col :span="8">
                <label>线路类型:</label><span v-text="userForm.circuitType"></span>
              </el-col>
              <el-col :span="8">
                <label>平台类型:</label><span v-text="userForm.platformType"></span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <label>账号类型:</label><span v-text="userForm.accountType"></span>
              </el-col>
              <el-col :span="8">
                <label>账号名称:</label><span v-text="userForm.accountName"></span>
              </el-col>
              <el-col :span="8">
                <label>部门:</label><span v-text="userForm.departmentName"></span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <label>角色:</label><span v-text="userForm.roleName"></span>
              </el-col>
              <el-col :span="8">
                <label>是否为移动:</label><span v-text="(userForm.isMove==0?'否':'是')"></span>
              </el-col>
              <el-col :span="8">
                <label>邮箱:</label><span v-text="userForm.email"></span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <label>状态:</label><span>{{showStatus(userForm.status)}}</span>
              </el-col>
              <el-col :span="8">
                <label>账号有效期:</label><span v-text="userForm.indate"></span>
              </el-col>
              <el-col :span="8">
                <label>权限等级:</label><span>{{showType(userForm.type)}}</span>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      deptData:[],
      selectedItem:'',//部门选中项
      drawer: false,//是否打开抽屉
      userData: [], // 用户数据列表
      accountName: [],
      departments: [],
      multipleSelection: [], // 多选选中的用户
      total: 0, // 总记录数
      queryMap: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页大小
        clientName: "", // 客户名称
        nickName: "", // 用户昵称
        userName: "", // 用户名
        phone: "", // 手机号码
        deptId: "", // 部门
        accountName: "", // 账号
        status: "", // 状态
      },
      userForm: [],
      option: {
        label: 'deptName', // 树形结构中每个节点的标签属性
        value: 'deptId', // 树形结构中每个节点的值属性
        children: 'children' // 树形结构中每个节点的子节点属性
      },
    };
  },
  methods: {
    selectDeptID(data){
      this.selectedItem=data.deptName;
      this.queryMap.deptId=data.deptId;
    },
    // 返回按钮事件
    goBack() {
      console.log('返回上一页');
    },
    // 处理表格选择变化
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 处理分页大小变化
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getUserList();
    },
    // 处理当前页变化
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getUserList();
    },
    // 查询按钮事件
    search() {
      this.queryMap.pageNum = 1;
      this.getUserList();
    },
    //加载菜单树
    async getDepartmentList() {
      const {data: res} = await this.$http.get("system/dept/tree");
      if (res.success) {
        //console.log("-----------------------------------")
        //console.log(JSON.stringify(res.data.tree))
        this.deptData=res.data.tree;
      }
    }, transformDeptStructure(data) {
      const transform = (node) => {
        const newNode = {
          name: node.deptName,
          value: node.total || 0 // 强制所有节点必须有 value
        };

        // 递归处理子节点，并过滤空 children
        if (node.children && node.children.length > 0) {
          const children = node.children.map(transform).filter(c =>
              c.value > 0 || (c.children && c.children.length > 0)
          );

          if (children.length > 0) { // 仅当存在有效子节点时添加 children
            newNode.children = children;
            newNode.value += children.reduce((sum, c) => sum + c.value, 0); // 累加子节点值
          }
        }

        return newNode;
      };

      return data.map(transform).filter(n =>
          n.value > 0 || (n.children && n.children.length > 0)
      );
    },
// 重置按钮事件
    reset() {
      this.queryMap = {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页大小
        clientName: "", // 客户名称
        nickName: "", // 用户昵称
        userName: "", // 用户名
        phone: "", // 手机号码
        deptId: "", // 部门
        roleId: "", // 角色
        status: "", // 状态
      };
      // 清空部门数据
      this.deptData = [];
      // 清空选中的部门项
      this.selectedItem = '';
    },
    //得到用户集合
    async getUserList() {
      const { data: res } = await this.$http.get("/system/user/qt/getUserByEmpId", {
        params: this.queryMap
      });
      if(!res.success){
        return this.$message.error("获取用户列表失败:"+res.data.errorMsg);
      }
      this.total = res.data.total;
      this.userData=res.data.rows;
    },
    async selectUserById(id){
      const { data: res } = await this.$http.get("/system/user/qt/selectUser/"+id);
      if(!res.success){
        return this.$message.error("获取用户详情失败:"+res.data.errorMsg);
      }
      this.userForm = res.data;
      console.log(this.userForm);
      this.drawer = true;
    },
    // 批量删除 选中用户
    deleteSelected() {
      const ids = this.multipleSelection.map(row => row.userId);
      if (ids.length>0) {
        this.deleteUser(ids);
      }else {
        this.$message.warning({
          title:'操作失败',
          message:"请选择要删除的用户",
        });
      }
    },
    //删除或批量删除
    async deleteUser(id){
      const res = await this.$confirm(
          id.length>1?"此操作将会把选中的用户删除, 是否继续?":"此操作将会把此用户删除, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res === "confirm") {
        const { data: res } = await this.$http.delete("/system/user/qt/userDelete/" + id);
        console.log(res);
        if(res.success){
          this.$notify.success({
            title:'操作成功',
            message:id.length>1?"选中的用户已成功删除":"此用户成功删除",
          });
          await this.getUserList();
        }else {
          this.$message.error(res.data.errorMsg);
        }
      }
    },
    /**
     * 冻结-1   下线：-2
     */
    async updateStatus(id,status){
      const res = await this.$confirm(
          "确定要"+this.selectUpdateStatus(status)+"该用户吗?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消操作"
        });
      });
      if (res === "confirm") {
        const { data: res } = await this.$http.put("/system/user/qt/userUpdateStatus/" + id+ "/"+this.selectUpdateStatusNum(status));
        console.log(res);
        if(res.success){
          this.$notify.success({
            title:'操作成功',
            message:'用户状态更新成功',
          });
          await this.getUserList();
        }else {
          this.$message.error(res.data.errorMsg);
        }
      }
    },
    async updatePwd(id){
      const res = await this.$confirm(
          "确定要将该用户的密码重置吗?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消操作"
        });
      });
      if (res === "confirm") {
        const {data: res} = await this.$http.post("system/user/qt/updatePwd",
            {
              userId: id,
              password: '123456'
            }
        );
        if (res.success) {
          this.$alert('重置密码成功，初始密码是123456', '提示', {
            confirmButtonText: '确定',
            callback: action => {

            }
          });
        }
      }
    },
    /**
     * 获得部门信息
     */
    async getDeptClientList() {
      if (this.queryMap.accountName==null || this.queryMap.accountName==0){
        this.deptData=[]
      }else {
        this.queryMap.deptId = "";
        const {data: res} = await this.$http.get("/system/dept/findDeptByAccountName/"+this.queryMap.accountName);
        if (!res.success) {
          return this.$message.error("获取部门信息失败:" + res.data.errorMsg);
        }
        this.deptData=res.data.tree;
      }

    },
    /**
     * 获得账号信息
     */
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data.errorMsg);
      }
      this.accountName = res.data

    },

    /**
     * 用户权限等级
     */
    showType(type){
      if (type==0){
        return "超级管理员"
      }else if (type==1){
        return "部门管理员"
      }else {
        return "系统用户"
      }
    },
    /**
     * 用户状态
     */
    showStatus(status){
      if (status === 0){
        return '未开启外呼'
      }else if (status === 1){
        return '已开启外呼'
      }else if (status === -1){
        return '冻结'
      }else if (status === -2){
        return '下线（离职，进入离职分配列表中）'
      }
    },
    //当鼠标悬停在按钮上时，出现的文字，冻结或解冻
    selectUpdateStatus(status){
      if (status === -1){
        return '解冻'
      }else{
        return '冻结'
      }
    },
    //冻结或解冻，传入后台的值
    selectUpdateStatusNum(status){
      if (status === -1){
        return 0
      }else{
        return -1
      }
    },
  },
  created() {
    this.getUserList();
    this.getAccountNameList();
  },
};
</script>

<style scoped>
.el-select-dropdown__item.hover{
  background-color: #fff !important;
}
.hint {
  margin-left: 2vh;
  font-weight: 400;
  font-size: 12px;
  color: red;
}

/* 弹出层样式 */
.popups .el-main {
  background-color: #fff;
  margin: 15vh auto;
}

.popups .el-main .header {
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}

.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}

/* 行间距 */
.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

/* 列样式 */
.el-row .el-col {
  font-size: 14px;
}

.el-row .el-col label {
  color: #5e6d82;
}

/* 操作列样式 */
.el-table__body .el-table__row td:nth-child(13) {
  width: 200px;
  position: fixed;
  right: 0;
  background-color: #fff;
  box-shadow: -2px 0 5px rgba(0,0,0,0.1);
}

.el-table__body .el-table__row td:nth-child(13) .el-button {
  margin: 0 5px;
}
</style>